import 'package:dio/dio.dart';
import '../models/ai_chat_response.dart';
import 'dart:async';

class AIChatService {
  static const String baseUrl = 'https://api.wiseaii.com/wiseai/v1';
  final Dio _dio = Dio(
    BaseOptions(baseUrl: baseUrl, contentType: 'application/json'),
  );

  Future<AIChatResponse> sendMessage({
    required String bundleId,
    required String sessionId,
    required String content,
    String? conversationId,
  }) async {
    try {
      final response = await _dio.post(
        '/chat',
        data: {
          'bundle_id': bundleId,
          'session_id': sessionId,
          'content_type': 'text',
          'content': content,
          if (conversationId != null) 'conversation_id': conversationId,
        },
      );

      return AIChatResponse.fromJson(response.data);
    } on DioException catch (e) {
      throw '网络请求失败: ${e.message}';
    } catch (e) {
      throw '发送消息失败: $e';
    }
  }

  // 添加流式响应方法
  Stream<String> sendMessageStream({
    required String bundleId,
    required String sessionId,
    required String content,
    String? conversationId,
  }) async* {
    try {
      // 模拟流式响应
      // 注意：实际实现应连接到支持流式响应的API
      final response = await _dio.post(
        '/chat',
        data: {
          'bundle_id': bundleId,
          'session_id': sessionId,
          'content_type': 'text',
          'content': content,
          if (conversationId != null) 'conversation_id': conversationId,
        },
      );

      final chatResponse = AIChatResponse.fromJson(response.data);
      final answer = chatResponse.data.answer ?? '';

      // 保存conversationId以供后续使用
      _latestConversationId = chatResponse.data.conversationId;

      // 模拟字符流式返回
      final characters = answer.split('');

      // 初始输出为空字符串
      String currentText = '';

      // 每次添加一个字符并yield
      for (var char in characters) {
        await Future.delayed(const Duration(milliseconds: 50));
        currentText += char;
        yield currentText;
      }
    } on DioException catch (e) {
      throw '网络请求失败: ${e.message}';
    } catch (e) {
      throw '发送消息失败: $e';
    }
  }

  // 保存最近的conversationId
  String? _latestConversationId;

  // 获取最近的conversationId
  String? get latestConversationId => _latestConversationId;
}
